package application

import (
	"forum/internal/common"
	"forum/internal/domain"
	"forum/internal/domain/repo"
	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
)

type UserService interface {
	SignupByEmail(ctx *gin.Context, user domain.User) error
	LoginByEmail(ctx *gin.Context, user domain.User) (domain.User, error)
}

type UserServiceImp struct {
	userRepo repo.UserRepository
}

func NewUserServiceImp(userRepo repo.UserRepository) *UserServiceImp {
	return &UserServiceImp{userRepo: userRepo}
}

func (u *UserServiceImp) SignupByEmail(ctx *gin.Context, user domain.User) error {
	hash, err := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost)
	if err != nil {
		return err
	}
	user.Password = string(hash)
	return u.userRepo.Save(ctx, user)
}

func (u *UserServiceImp) LoginByEmail(ctx *gin.Context, user domain.User) (domain.User, error) {

	result, err := u.userRepo.FindByEmail(ctx, user)
	if err != nil {
		return domain.User{}, err
	}
	err = bcrypt.CompareHashAndPassword([]byte(result.Password), []byte(user.Password))
	if err != nil {
		return domain.User{}, common.ErrPassword
	}
	return result, err
}
